package com.sky.service.impl;

import com.sky.dto.ReportQueryDTO;
import com.sky.entity.Orders;
import com.sky.exception.PermissionDeniedException;
import com.sky.mapper.ReportMapper;
import com.sky.service.WorkSpaceService;
import com.sky.vo.*;
import com.sun.deploy.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class WorkSpaceServiceImpl implements WorkSpaceService {
    @Autowired
    ReportMapper reportMapper;

    @Override
    public BusinessDataVO businessData() {
        String Nowdate=LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        Integer newUser = reportMapper.querynewUser(Nowdate);
        ReportQueryDTO reportQueryDTO=new ReportQueryDTO();
        reportQueryDTO.setBegin(Nowdate);
        reportQueryDTO.setEnd(Nowdate);
        List<Orders> orders=reportMapper.queryOrders(reportQueryDTO);
        Map<String,Map<String,String>> data=new HashMap<>();
        orders.forEach((item)->{
            String key=item.getOrderTime().toLocalDate().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            Map value= data.get(key);
            if(value!=null){
                Integer orderCount =(Integer)value.get("orderCount");
                Integer validOrderCount =(Integer)value.get("validOrderCount");
                orderCount+=1;
                if(item.getStatus()==5){
                    validOrderCount+=1;
                }
                value.put("orderCount",orderCount);
                value.put("validOrderCount",validOrderCount);
                data.put(key,value);
            }else{

                Map v1=new HashMap();
                v1.put("orderCount",1);
                if(item.getStatus()==5){
                    v1.put("validOrderCount",1);
                }else{
                    v1.put("validOrderCount",0);
                }
                data.put(key,v1);
            }

        });

        Integer totalValidOrderCount=0;
        Double orderCompletionRate=0d;
        for (Map.Entry entry : data.entrySet()) {
            String key = (String)entry.getKey();
            Map value = (Map) entry.getValue();
            totalValidOrderCount+=(Integer) value.get("validOrderCount");

        }
        if(orders.size()>0){
            orderCompletionRate=totalValidOrderCount/(orders.size()+0.0);
        }

        BigDecimal turnover  = reportMapper.queryComplateOrders(reportQueryDTO.getBegin());
        Integer count  = reportMapper.queryComplateOrdersCount(reportQueryDTO.getBegin());
        BigDecimal unitPrice=new BigDecimal("0");
        if(count>0){
            unitPrice=turnover.divide(new BigDecimal(count));
        }

        return BusinessDataVO.builder()
                .newUsers(newUser)
                .orderCompletionRate(orderCompletionRate)
                .validOrderCount(totalValidOrderCount)
                .turnover(turnover.doubleValue())
                .unitPrice(unitPrice.doubleValue())
                .build();
    }

    @Override
    public SetmealOverViewVO overviewSetmeals() {
        Integer dis=reportMapper.querySetmealCount(0);
        Integer sold=reportMapper.querySetmealCount(1);

        return SetmealOverViewVO.builder()
                .discontinued(dis)
                .sold(sold)
                .build();
    }

    @Override
    public DishOverViewVO overviewDishes() {
        Integer dis=reportMapper.queryDishCount(0);
        Integer sold=reportMapper.queryDishCount(1);

        return DishOverViewVO.builder()
                .discontinued(dis)
                .sold(sold)
                .build();
    }

    @Override
    public OrderOverViewVO overviewOrders() {
        //订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款
        List<Orders> orders = reportMapper.queryOrders1();
        Integer cancelC=0;
        Integer completedOrders=0;
        Integer deliveredOrders=0;
        Integer waitingOrders=0;

        for (Orders order : orders) {
            if(order.getStatus()==6){
                cancelC++;
            }
            if(order.getStatus()==5){
                completedOrders++;
            }
            if(order.getStatus()==3){
                deliveredOrders++;
            }
            if(order.getStatus()==2){
                waitingOrders++;
            }
        }



        return OrderOverViewVO.builder()
                .allOrders(orders.size())
                .cancelledOrders(cancelC)
                .completedOrders(completedOrders)
                .deliveredOrders(deliveredOrders)
                .waitingOrders(waitingOrders)
                .build();
    }


    private OrderReportVO getOrdersStatistics(ReportQueryDTO reportQueryDTO){

        LocalDate begin = LocalDate.parse(reportQueryDTO.getBegin());
        LocalDate end = LocalDate.parse(reportQueryDTO.getEnd());

        long daysDifference = ChronoUnit.DAYS.between(begin, end);

        if(daysDifference<0){
            throw new PermissionDeniedException("时间有误");
        }


        String localDate="";
        List<String> dateList=new ArrayList();
        List<String> counttList=new ArrayList<>();
        List<String> vcounttList=new ArrayList<>();
        Integer orderCount=0;
        Integer validOrderCount=0;


        dateList.add(reportQueryDTO.getBegin());
        for (int i=0;i<daysDifference;i++){
            begin=begin.plusDays(1);
            localDate = begin.toString();
            dateList.add(localDate);
        }
        for (String item : dateList) {
            Integer count = reportMapper.queryOrdersCount(item);
            Integer vcount = reportMapper.queryValidOrdersCount(item);
            counttList.add(count.toString());
            vcounttList.add(vcount.toString());
            orderCount+=count;
            validOrderCount+=vcount;
        }


        Double orderCompletionRate=validOrderCount/(orderCount+0.0);


        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCompletionRate(orderCompletionRate)
                .orderCountList(StringUtils.join(counttList,","))
                .validOrderCountList(StringUtils.join(vcounttList,","))
                .totalOrderCount(orderCount)
                .validOrderCount(validOrderCount)
                .build();
    }
    public TurnoverReportVO getTurnoverStatistics(ReportQueryDTO reportQueryDTO) {
        LocalDate begin = LocalDate.parse(reportQueryDTO.getBegin());
        LocalDate end = LocalDate.parse(reportQueryDTO.getEnd());

        long daysDifference = ChronoUnit.DAYS.between(begin, end);

        if(daysDifference<0){
            throw new PermissionDeniedException("时间有误");
        }


        String localDate="";
        List<String> dateList=new ArrayList();
        List<String> amountList=new ArrayList<>();
        dateList.add(reportQueryDTO.getBegin());
        for (int i=0;i<daysDifference;i++){
            begin=begin.plusDays(1);
            localDate = begin.toString();
            dateList.add(localDate);
        }

        dateList.forEach((item)->{
            BigDecimal amount = reportMapper.queryComplateOrders(item);
            amountList.add(amount.toString());
        });

        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(amountList,","))
                .build();
    }
    public UserReportVO getUserStatistics(ReportQueryDTO reportQueryDTO) {
        LocalDate begin = LocalDate.parse(reportQueryDTO.getBegin());
        LocalDate end = LocalDate.parse(reportQueryDTO.getEnd());

        long daysDifference = ChronoUnit.DAYS.between(begin, end);

        if(daysDifference<0){
            throw new PermissionDeniedException("时间有误");
        }


        String localDate="";
        List<String> dateList=new ArrayList();
        List<String> totalList=new ArrayList<>();
        List<String> newUserList=new ArrayList<>();
        dateList.add(reportQueryDTO.getBegin());
        for (int i=0;i<daysDifference;i++){
            begin=begin.plusDays(1);
            localDate = begin.toString();
            dateList.add(localDate);
        }
        dateList.forEach((item)->{
            Map total=reportMapper.queryTotal(item);
            Integer newUser=reportMapper.querynewUser(item);
            newUserList.add(newUser.toString());
            totalList.add(total.get("count").toString());
        });

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .totalUserList(StringUtils.join(totalList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .build();
    }
}
